<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <!-- 动态组件在默认情况下，切换的时候是会自动地卸载和重新创建 -->
      <h2>动态组件 - keepalive</h2>
      <button @click="str = 'Child1'">com1</button>
      <button @click="str = 'Child2'">com2</button>
      <button @click="str = 'Child3'">com3</button>

      <!-- 缓存组件 -->
      <keep-alive>
        <component :is="str"></component>
      </keep-alive>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      const { createApp } = Vue;

      const Child1 = {
        mounted() {
          console.log("child1 mounted");
        },
        beforeUnmount() {
          console.log("child1 beforeUnmount");
        },
        template: `
          <div>child1组件</div>
        `,
      };

      let timer;
      const Child2 = {
        data() {
          return {
            count: 1,
          };
        },
        mounted() {
          console.log("child2 mounted");
          // setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeUnmount() {
          console.log("child2 beforeUnmount");
        },
        // 缓存组件重新激活时调用
        activated() {
          console.log("child2 activated");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        // 缓存组件失活时调用
        deactivated() {
          console.log("child2 deactivated");
          clearInterval(timer);
        },
        template: `
          <div>child2组件 - {{ count }} - <button @click="count++">btn</button></div>
        `,
      };

      const Child3 = {
        mounted() {
          console.log("child3 mounted");
        },
        beforeUnmount() {
          console.log("child3 beforeUnmount");
        },
        template: `
          <div>child3组件</div>
        `,
      };

      createApp({
        data() {
          return {
            str: "Child1",
          };
        },
        components: {
          Child1,
          Child2,
          Child3,
        },
      }).mount("#app");
    </script>
  </body>
</html>
